<?php


namespace app\api\controller;
use app\api\model\Token;

class Wxutils
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    private static $appid = null; //小程序appid
    private static $secret = null; //小程序secret
    private static $gzhappid = null; //公众号appid
    private static $gzhsecret = null; //公众号secret

    private static function init()
    {
        self::$appid = config('wxconfig.appid');
        self::$secret = config("wxconfig.appSecret");
        self::$gzhappid = config('wxconfig.gzhappid');
        self::$gzhsecret = config("wxconfig.gzhappSecret");

    }

    /**
     * 获取微信account_tokey
     * @param int $type 1=小程序，2=公众号
     * @return mixed|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function get_access_token($type=1){
        self::init();
        if($type==1){
            //查询token
            $token = Token::where('name','wxapp')->find();
            //判断token是否过期
            if(!$token || empty($token['access_token']) || $token['token_time']<(time()-7100)){
                //重新获取token
                $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".self::$appid."&secret=".self::$secret;
                $res = http_curl($url);
                $res = json_decode($res,true);
                //保存token
                if(isset($res['access_token'])){
                    $upok = Token::where('name','wxapp')->update(['access_token'=>$res['access_token'],'token_time'=>time(),'expires_in'=>$res['expires_in']]);
                    return $res['access_token'];
                }else{
                    return null;
                }
            }
        }else{
            //查询token
            $token = Token::where('name','wxgzh')->find();
            //判断token是否过期
            if(!$token || empty($token['access_token']) || $token['token_time']<(time()-7100)){
                //重新获取token
                $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".self::$gzhappid."&secret=".self::$gzhsecret;
                $res = http_curl($url);
                $res = json_decode($res,true);
                //保存token
                if(isset($res['access_token'])){
                    $upok = Token::where('name','wxgzh')->update(['access_token'=>$res['access_token'],'token_time'=>time(),'expires_in'=>$res['expires_in']]);
                    return $res['access_token'];
                }else{
                    return null;
                }
            }
        }

        return $token['access_token'];
    }

    public static function get_unionid($openid){
        $accessToken = self::get_access_token();
        $url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token={$accessToken}&openid={$openid}&lang=zh_CN";
        $res = http_curl($url);
        $res = json_decode($res,true);
        return $res;
    }

    public static function get_gzh_unionid($openid){
        $accessToken = self::get_access_token(2);
        $url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token={$accessToken}&openid={$openid}&lang=zh_CN";
        $res = http_curl($url);
        $res = json_decode($res,true);
        return $res;
    }

    /**
     * 微信小程序获取openid
     * @param $code
     * @return mixed
     */
    public static function get_openid($code){
        self::init();
        //小程序调用
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid=".self::$appid."&secret=".self::$secret."&js_code=".$code."&grant_type=authorization_code";
        $res = http_curl($url);
        $res = json_decode($res,true);
        return $res;
    }

    public static function getWxACodeUnlimit($path,$uid){
        $qrcodepath = "uploads/qrcode/shop/";
        !is_dir($qrcodepath) && mkdir($qrcodepath, 0777, true);
        $filename = $qrcodepath.'qrcode_'.$uid.'.png';
        if(is_file($filename)){
            return $filename;
        }

        $accessToken = self::get_access_token(1);
        $url = "https://api.weixin.qq.com/wxa/getwxacode?access_token={$accessToken}";
        $data = [
            'path' => $path, // 扫码后进入的小程序页面路径
            'width' => 430, // 二维码宽度，单位px，默认430
            'auto_color' => false, // 自动配置线条颜色，如果颜色依然是黑色，则说明不建议配置主色调
            'is_hyaline' => false, // 是否需要透明底色，为true时，生成透明底色的小程序码
            //'page' => $path, // 扫码进入的页面路径
            //'query' => 'uid='.$uid, // 二维码携带的参数
            'scene' => 'uid=' . $uid,// 二维码携带的参数
        ];
        $result = http_curl($url,'post',json_encode($data),"Content-Type: application/json");
        if(isset($result['errcode'])){
            return null;
        }
        // 将返回的二进制数据保存为图片
        file_put_contents($filename, $result);
        chmod($filename, 0777);
        return $filename;
    }
    public static function getWxACodeUnlimitUser($path,$uid){
        $qrcodepath = "uploads/qrcode/user/";
        !is_dir($qrcodepath) && mkdir($qrcodepath, 0777, true);
        $filename = $qrcodepath.'qrcode_'.$uid.'.png';
        if(is_file($filename)){
            return $filename;
        }
        $accessToken = self::get_access_token(1);
        $url = "https://api.weixin.qq.com/wxa/getwxacode?access_token={$accessToken}";
        $data = [
            'path' => $path, // 扫码后进入的小程序页面路径
            'width' => 430, // 二维码宽度，单位px，默认430
            'auto_color' => false, // 自动配置线条颜色，如果颜色依然是黑色，则说明不建议配置主色调
            'is_hyaline' => false, // 是否需要透明底色，为true时，生成透明底色的小程序码
            //'page' => $path, // 扫码进入的页面路径
            //'query' => 'uid='.$uid, // 二维码携带的参数
            'scene' => 'uid=' . $uid,// 二维码携带的参数
        ];
        $result = http_curl($url,'post',json_encode($data),"Content-Type: application/json");
        if(isset($result['errcode'])){
            return null;
        }
        // 将返回的二进制数据保存为图片
        file_put_contents($filename, $result);
        chmod($filename, 0777);
        return $filename;
    }

    public Static function getuserinfo(){
        $user = session('authuser');
        $accessToken = self::get_access_token();
        $userInfoUrl = "dfa329b17bc7cd6965aee30d57c8c807.jpg";
        $userInfoResponse = file_get_contents($userInfoUrl);
        $userInfo = json_decode($userInfoResponse, true);
        return $userInfo;
    }
}